package com.example.demo;


import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.collections.map.HashedMap;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

public class XmlUtil {

    public static void main(String[] args) throws Exception {
        Map<String, Object> sd = new HashedMap();
        sd.put("name", "xidaodao");
        JSONObject jsonObject = JSONObject.fromObject(sd);
        String s = json2Xml(jsonObject);
        System.out.println(s);
        strChangeXML(s);

    }

    public String xmlChangeString(String fileName) {
        try {
            SAXReader saxReader = new SAXReader();// 新建一个解析类
            Document tempDocument = saxReader.read(new File(fileName));
            return tempDocument.asXML();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }


    // 将字符串string类型转换成xml文件
    public static void strChangeXML(String str) throws IOException {
        SAXReader saxReader = new SAXReader();
        Document document;
        try {
            document = saxReader.read(new ByteArrayInputStream(str.getBytes("UTF-8")));
            OutputFormat format = OutputFormat.createPrettyPrint();
            /** 将document中的内容写入文件中 */
            XMLWriter writer = new XMLWriter(new FileWriter(new File("E:\\11111.xml")), format);
            writer.write(document);
            writer.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    public static String json2Xml(JSONObject json) throws DocumentException {
        String sXml = "";
        XMLSerializer xmlSerializer = new XMLSerializer();
        xmlSerializer.setTypeHintsEnabled(false);
        //xmlSerializer.setRootName(rootName);
        String sContent = xmlSerializer.write(json, "utf-8");
        try {
            Document docCon = DocumentHelper.parseText(sContent);
            sXml = docCon.getRootElement().asXML();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return sXml;
    }


}